{% extends 'sales/base.html' %}
{% load static %}
{% block breadcrumb %}
<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li class="breadcrumb-item"><a href="{% url 'events:event_create' %}">Events</a></li>
    <li class="breadcrumb-item active">{% if event_obj %}Edit{% else %}Create{% endif %}</li>
  </ol>
</nav>
{% endblock %}
{% block content %}
<form id="formid" action='' method="POST" novalidate enctype="multipart/form-data">
  <div class="overview_form_block row marl justify-content-center">
    <div class="col-md-9">
      <div class="card">
        <div class="card-body">
          <div class="card-title text-center">
            {% if event_obj %}EDIT{% else %}CREATE{% endif %} EVENT
          </div>
          <div class="row marl">
            <div class="col-md-4">
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1" class="required">Event
                    Name{% if form.name.field.required %}<span class="error_marker"
                      style="color:red">*</span>{% endif %}</label>
                  {{ form.name }}
                  <span class="error" id="id__name">{{ form.name.errors }}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1">Event Type{% if form.event_type.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  {{ form.event_type }}
                  <span class="error" id="id__event_type">{{ form.event_type.errors }}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group">
                  <label for="exampleInputEmail1" class="required">Contacts{% if form.contacts.field.required %}<span
                      class="error_marker" style="color:red">*</span>{% endif %}</label>
                  {{ form.contacts }}
                  <span class="error" id="id__contacts">{{ form.contacts.errors }}</span>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="filter_col billing_block col-md-12" style="padding: 0px;">
                <div class="filter_col col-md-12">
                  <div class="form-group">
                    <label for="exampleInputEmail1" class="required">Start
                      Date{% if form.start_date.field.required %}<span class="error_marker"
                        style="color:red">*</span>{% endif %}</label>
                    {{ form.start_date }}
                    <span class="error" id="id__start_date">{{ form.start_date.errors }}</span>
                  </div>
                </div>
                <div class="filter_col col-md-12">
                  <div class="form-group">
                    <label for="exampleInputEmail1" class="required">Start
                      Time{% if form.start_time.field.required %}<span class="error_marker"
                        style="color:red">*</span>{% endif %}</label>
                    {{ form.start_time }}
                    <span class="error" id="id__start_time">{{ form.start_time.errors }}</span>
                  </div>
                </div>
                <div class="filter_col col-md-12">
                  <div class="form-group ">
                    <label for="exampleInputEmail1" class="required">End Date{% if form.end_date.field.required %}<span
                        class="error_marker" style="color:red">*</span>{% endif %}</label>
                    {{ form.end_date }}
                    <span class="error" id="id__end_date">{{ form.end_date.errors }}</span>
                  </div>
                </div>
                <div class="filter_col col-md-12">
                  <div class="form-group end_time_selector">
                    <label for="id_contacts" class="required">End Time{% if form.end_time.field.required %}<span
                        class="error_marker" style="color:red">*</span>{% endif %}</label>
                    {{ form.end_time }}
                    <span class="error" id="id__end_time">{{ form.end_time.errors }}</span>
                  </div>
                </div>
                <div class="filter_col billing_block col-md-12" style="padding: 0px;">
                </div>
              </div>
            </div>
            <div class="col-md-4">
              {% if request.user.is_superuser or request.user.role == 'ADMIN' %}
              <div class="filter_col col-12">
                <div class="form-group">
                  <label for="id_sattus">Teams {% if form.teams.field.required %}<span
                      class="error">*</span>{% endif %}</label>
                  <select name="teams" id="id_teams" class="assigned_users form-control" multiple>
                    {% for team in teams %}
                    <option data-users="{{team.get_users}}" value="{{team.id}}" {% if team in event_obj.teams.all %}
                      selected="" {% endif %}>
                      {{team}}</option>
                    {% endfor %}
                  </select>
                  <span class="error" id="id__teams">{{ form.teams.errors }}</span>
                </div>
              </div>

              <div class="filter_col col-12">
                <div class="form-group">
                  <label for="id_sattus"><span class="">Users</span></label>
                  <select name="" aria-readonly="true" id="_id_assigned_to" class=" form-control" multiple>
                    {% if event_obj and event_obj.teams.all %}
                    {% for user in users %}
                    {% if user in event_obj.get_team_users %}
                    <option value="{{user.id}}" selected="">{{user.email}}</option>
                    {% else %}
                    <option value="{{user.id}}">{{user.email}}</option>
                    {% endif %}
                    {% endfor %}
                    {% else %}
                    {% for user in users %}
                    <option value="{{user.id}}">{{user.email}}</option>
                    {% endfor %}
                    {% endif %}
                  </select>
                </div>
              </div>

              {% endif %}
              <div class="filter_col col-md-12">
                <div class="form-group">
                  
                  <select class="assigned_users form-control" name="assigned_to" multiple="multiple"
                    id="id_assigned_to">
                    {% for user in users %}
                    <option value="{{user.id}}" {% if user in event_obj.get_assigned_users_not_in_teams or user.id in assignedto_list %}
                      selected="" {% endif %}>{{user.email}}</option>
                    {% endfor %}
                  </select>
                  <span class="error error_message" id="error_id_assigned_to">{{ form.assigned_to.errors }}</span>
                </div>
              </div>
              <div class="filter_col col-md-12">
                <div class="form-group ">
                  <label for="id_contacts" class="required">Description{% if form.description.field.required %}<span
                      class="error_marker" style="color:red">*</span>{% endif %}</label>
                  {{ form.description }}
                  <span class="error" id="id__description">{{ form.description.errors }}</span>
                </div>
              </div>
              {% if not event_obj %}
              <div class="filter_col col-md-12" id="recurring_block">
                <p class="mt-3" style="color: #333">Days</p>
                <div class="form-check mb-1">
                  <input type="checkbox" class="form-check-input" name="recurring_days" id="" value="Monday"
                    {% if 'Monday' in selected_recurring_days %} checked {% endif %}>
                  <label class="form-check-label" for="exampleCheck1">Monday</label>
                </div>
                <div class="form-check mb-1">
                  <input type="checkbox" class="form-check-input" name="recurring_days" id="" value="Tuesday"
                    {% if 'Tuesday' in selected_recurring_days %} checked {% endif %}>
                  <label class="form-check-label" for="exampleCheck1">Tuesday</label>
                </div>
                <div class="form-check mb-1">
                  <input type="checkbox" class="form-check-input" name="recurring_days" id="" value="Wednesday"
                    {% if 'Wednesday' in selected_recurring_days %} checked {% endif %}>
                  <label class="form-check-label" for="exampleCheck1">Wednesday</label>
                </div>
                <div class="form-check mb-1">
                  <input type="checkbox" class="form-check-input" name="recurring_days" id="" value="Thursday"
                    {% if 'Thursday' in selected_recurring_days %} checked {% endif %}>
                  <label class="form-check-label" for="exampleCheck1">Thursday</label>
                </div>
                <div class="form-check mb-1">
                  <input type="checkbox" class="form-check-input" name="recurring_days" id="" value="Friday"
                    {% if 'Friday' in selected_recurring_days %} checked {% endif %}>
                  <label class="form-check-label" for="exampleCheck1">Friday</label>
                </div>
                <div class="form-check mb-1">
                  <input type="checkbox" class="form-check-input" name="recurring_days" id="" value="Saturday"
                    {% if 'Saturday' in selected_recurring_days %} checked {% endif %}>
                  <label class="form-check-label" for="exampleCheck1">Saturday</label>
                </div>
                <div class="form-check mb-1">
                  <input type="checkbox" class="form-check-input" name="recurring_days" id="" value="Sunday"
                    {% if 'Sunday' in selected_recurring_days %} checked {% endif %}>
                  <label class="form-check-label" for="exampleCheck1">Sunday</label>
                </div>
                <div>
                  <span id="id__recurring_days" class="error"></span>
                </div>
              </div>
              {% endif %}
            </div>
          </div>
          <div class="col-md-12">
            <div class="col-md-12">
              <div class="row marl buttons_row form_btn_row text-center">
                <button class="btn btn-default save" type="submit">Save</button>
                <a href="{% url 'events:events_list' %}" class="btn btn-default clear"
                  id="create_user_cancel">Cancel</a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
  </div>
  
</form>
{% endblock %}
{% block js_block %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript">

  // $(document).ready(function() {
  //   $('.assigned_users').select2();
  // });
  $(document).ready(function () {
    $('#_id_assigned_to').select2({ disabled: 'readonly' });
    $('#recurring_block').hide()
    $("#id_contacts").select2();
    $("#id_assigned_to").select2();
    $("#id_teams").select2();
    $("#id_start_date").css('color', 'black');
    $("#id_end_date").css('color', 'black');
    var date = new Date();
    var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    $('#id_start_date, #id_end_date').datetimepicker({
      'format': 'YYYY-MM-DD',
      minDate: today
    })
    $('#id_start_time, #id_end_time').datetimepicker({
      'format': 'HH:mm:ss',
      icons: {
        time: "far fa-clock",
        up: "fas fa-chevron-up",
        down: "fas fa-chevron-down"
      }
    })
    if ($('#id_event_type').val() == 'Recurring') {
      $('#recurring_block').show()
    }
    else {
      $('#recurring_block').hide()
    }

    $('#id_event_type').on('change', function () {
      // console.log($(this).val())
      if ($(this).val() == 'Recurring') {
        $('#recurring_block').show()
      }
      else {
        $('#recurring_block').hide()
      }
    })
    // if ($('#recurring_block').length) {
    //   if ($('#id_event_type').val() == 'Recurring') {
    //     $('#recurring_block').show()
    //   }
    //   else {
    //     $('#recurring_block').hide()
    //   }
    // }

  });

  $('form#formid').ajaxForm({
    type: 'POST',
    dataType: 'json',
    url: ".",
    data: $('#formid').serialize(),
    success: function (data) {
      if (data.error) {
        $('.error').html('')
        for (var key in data.errors) {
          $('#id__' + key).html("<p>" + data.errors[key][0] + "</p>");
        };
        $('#submit_btn').removeAttr('disabled')
      }
      else {
        window.location = data.success_url;
      }
    }
  });

  function find_dict(dict, id){
    var index = dict.map(function(o) { return o.team; }).indexOf(parseInt(id));
    return dict[index]['users']
  }

  $("#id_teams").change(function (e) {
    var teams = []
    var all_users = []
    var selected_teams = []
    var selected_users = []
    var assigned_users = []
    $.get("{% url 'events:get_teams_and_users' %}", function(data){
      // console.log(data)
          if(($('#id_teams').val()).length==0){
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
        $('#id_assigned_to').select2().trigger('change');

          }

      teams = data['teams']
      all_users = data['users']
      try {
        var users = []
        $('#id_teams option:selected').each(function () {
          // users.push($(this).attr('data-users'))
          _data = $(this).attr('data-users');
          selected_teams.push($(this).val())
          selected_users.push(find_dict(teams, $(this).val()))
          // console.log("s_users", selected_users)
          var un_select_users = [].concat.apply([], selected_users)
          // console.log('un select users', un_select_users);


        $('#id_assigned_to option').each(function () {
          if($.inArray(parseInt($(this).val()), un_select_users) != -1){
            $(this).attr('disabled', 'disabled')
            $('#id_assigned_to').select2();

          }
          else{
            $(this).show()
            $(this).removeAttr('disabled')
            $('#id_assigned_to').select2();

          }
          }
        )


          if (!selected_teams) {
            users = []
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
            $('#id_assigned_to').select2();
          } else {
            users = users.concat(_data.split(','))
          }
        });
        $('#id_teams option').each(function () {
          if ($(this).is(':selected')) {
            _data = $(this).attr('data-users').split(',')
            // console.log(' selected', $(this).attr('data-users').split(','))
            // console.log('selected', $(this).attr('data-users'))
          }
          else {
            _unselected = $(this).attr('data-users').split(',')
            // console.log('un selected', $(this).attr('data-users').split(','))
          }
        });
        // console.log('selected users teams data', users)
        var existingUsers = $('#id_assigned_to').val();
        var allUsers = users
        $('#_id_assigned_to').select2().val(allUsers).trigger('change');
        if (users.length) {

        }
      } catch (error) {
        console.log(error)
        $('#_id_assigned_to').select2().val([]).trigger('change');
      }
    })

  });

  $(document).ready(function($) {

    var teams = []
    var all_users = []
    var selected_teams = []
    var selected_users = []
    var assigned_users = []
    $.get("{% url 'events:get_teams_and_users' %}", function(data){

          if(($('#id_teams').val()).length==0){
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
        // $('#id_assigned_to').select2().val([]).trigger('change');

          }

      teams = data['teams']
      all_users = data['users']
      try {
        var users = []
        $('#id_teams option:selected').each(function () {
          // users.push($(this).attr('data-users'))
          _data = $(this).attr('data-users');
          selected_teams.push($(this).val())
          selected_users.push(find_dict(teams, $(this).val()))
          var un_select_users = [].concat.apply([], selected_users)


        $('#id_assigned_to option').each(function () {
          if($.inArray(parseInt($(this).val()), un_select_users) != -1){
            // $(this).attr('disabled', 'disabled')
            $(this).attr('disabled', 'disabled')
            $('#id_assigned_to').select2();

          }
          else{
            $(this).show()
            $(this).removeAttr('disabled')
            $('#id_assigned_to').select2();

          }
          }
        )


          if (!selected_teams) {
            users = []
            $('#id_assigned_to option').each(function () {
            $(this).removeAttr('disabled')
            })
            $('#id_assigned_to').select2();
          } else {
            users = users.concat(_data.split(','))
          }
        });
        $('#id_teams option').each(function () {
          if ($(this).is(':selected')) {
            _data = $(this).attr('data-users').split(',')
          }
          else {
            _unselected = $(this).attr('data-users').split(',')
          }
        });
        var existingUsers = $('#id_assigned_to').val();
        // var allUsers = users.concat(existingUsers)
        var allUsers = users
        // console.log(existingUsers)
        $('#_id_assigned_to').select2().val(allUsers).trigger('change');
        if (users.length) {

        }
      } catch (error) {
        console.log(error)
        $('#_id_assigned_to').select2().val([]).trigger('change');
      }
    })

  });
</script>
{% endblock js_block %}